package com.zang.blogz.strategy.context;

import com.zang.blogz.enmus.UploadStrategyEnum;
import com.zang.blogz.exception.BizException;
import io.github.vampireachao.stream.core.optional.Opp;
import com.zang.blogz.strategy.UploadStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.util.Map;

/**
 * @Author: ZVerify
 * @Description:  上传策略上下文
 * @DateTime: 2022/8/31 18:42
 **/
@Service
public class UploadStrategyContext {

    /**
     * 上传模式
     */
    @Value("${upload.mode}")
    private String uploadMode;

    @Autowired
    private Map<String, UploadStrategy> uploadStrategyMap;


    /**
     * 上传文件
     *
     * @param file 文件
     * @param path 路径
     * @return {@link String} 文件地址
     */
    public String executeUploadStrategy(MultipartFile file, String path) {

        Opp<String> ofTry = Opp.ofTry(() -> uploadStrategyMap.get(UploadStrategyEnum.getStrategy(uploadMode))
                .uploadFile(file, path), NullPointerException.class);

        if (Opp.of(ofTry.getException()).isPresent()) {

            throw new BizException("抱歉,请检查配置文件,当前没有你所选择的策略");
        }
        return ofTry.get();
    }

    /**
     * @param fileName 文件名称
     * @param inputStream 输入流
     * @param path 路径
     * @return {@link String}
     */
    public String executeUploadStrategy(String fileName, ByteArrayInputStream inputStream, String path){

        Opp<String> ofTry = Opp.ofTry(() -> uploadStrategyMap.get(UploadStrategyEnum.getStrategy(uploadMode))
                .uploadFile(fileName, inputStream, path), NullPointerException.class);

        if (Opp.of(ofTry.getException()).isPresent()) {

            throw new BizException("抱歉,请检查配置文件,当前没有你所选择的策略");
        }
        return ofTry.get();
    }
}
